package com.glodon.paas.databag.resource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.glodon.paas.databag.api.bean.TaskDto;
import com.glodon.paas.databag.service.TaskService;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.job.model.TaskStatus;
import com.glodon.paas.job.util.JsonUtil;

/**
 * 接收job-server的task进度报告.
 * 
 * @author botao.liao
 * 
 */
@Component
@Path("/task")
public class TaskResource {
    private final Logger logger = LoggerFactory.getLogger(TaskResource.class);
    @Autowired
    private TaskService taskService;

    @PUT
    @Path("/{taskId}")
    @Produces(MediaType.APPLICATION_JSON)
    public String precessTaskNotify(@PathParam("taskId") String taskId, InputStream is)
            throws IOException {
        String body = IOUtils.toString(is);
        logger.debug("receive task notify json:{}", body);
        
        Map<?, ?> map = null;
        try {
            map = JsonUtil.jsonToMap(body);
        } catch (Exception e) {
            throw PaasServerExceptionFactory.validateException("bad json string from job-server", e);
        }
        TaskDto task = convert2Dto(map);
        logger.info("receive task notify task:{}", task);
        boolean jobComplete = taskService.onTaskNotify(task);
        return Boolean.toString(jobComplete);
    }
    
    @SuppressWarnings("rawtypes")
    private TaskDto convert2Dto(Map map) {
        TaskDto dto = new TaskDto();
        dto.setTaskId((String)map.get("taskId"));
        dto.setProgress((Integer)((Map)map.get("values")).get("progress"));
        dto.setMessage((String)((Map)map.get("values")).get("message"));
        String status = (String)map.get("status");
        if (status == null) {
            throw PaasServerExceptionFactory.validateException("status cann't be empty.", null);
        }
        dto.setStatus(Enum.valueOf(TaskStatus.class, status));
        dto.setOutput((String)((Map)map.get("values")).get("output"));
        return dto;
    }
}
